# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

# ----------------------------------------------------------------------------
# Abstract class for logfiles
# ----------------------------------------------------------------------------

import logging,time,sys

logger = logging.getLogger()

class CLASSLOGF(object):
    
    def __init__(self, aLogfile):
        self._logfile = aLogfile
        self._handle = None
        self.name = 'LOG'
        self.type = 'LOGF'
        self.opened = False
        self.stop = False

    def open(self):
        logger.debug("Opening %s....",self._logfile)
        try:
            f = open(self._logfile)
            f.seek(0,2)
            self._handle = f
            logger.warning("Logfile %s opened",self._logfile)
            self.opened = True
        except Exception as e:
            logger.critical("%s : %s", repr(e.__class__), str(e))

    def close(self):
        self._handle.close()

    def flush(self):
        self._handle.flush()

    def write(self, line):
        try:
            wf = open(self._logfile,'ab')
            wf.write((line + "\n").encode('utf -8'))
            wf.close()
        except Exception as e:
            logger.error("%s : %s", repr(e.__class__), str(e))
        
    def read(self):
        try:
            line = self._handle.readline()
        except:
            line = None
        return line

    def follow(self,target):
        while not self.stop:
            line = self.read()
            if line:
                target.send(line)
            else:
                time.sleep(0.1)			
        
    def stops(self):
        self.stop = True
